<#systemSituation globalInfo="${globalInfo}"/>
<link rel="stylesheet" href="/static/css/metroStyle.css">
<!-- 防止页面数据重复定义,模板数据统一在此 -->
<!--:
    var typeList = dicttag.getDictList('menu_type');
    var ableList = dicttag.getDictList('show_hide');
    var typeJson = commontag.toJson(typeList);
    var ableJson = commontag.toJson(ableList);
    var isAdmin = usertag.isAdmin();
-->

<!-- widget grid -->
<section>

    <!-- row -->
    <div class="row">

        <!-- NEW WIDGET START -->
        <article class="col-xs-12 col-sm-12 col-md-12 col-lg-12">

            <div class="jarviswidget jarviswidget-color-blueDark" data-widget-editbutton="false">
                <header>
                    <span class="widget-icon"> <i class="fa fa-table"></i> </span>

                    <h2>菜单列表 </h2>

                </header>

                <div id="menu-list">

                    <!-- widget edit box -->
                    <div class="jarviswidget-editbox">
                        <!-- This area used as dropdown edit box -->
                    </div>
                    <!-- end widget edit box -->

                    <!-- widget content -->
                    <div class="widget-body no-padding">
                        <!-- office table toolbar -->
                        <div class="dt-toolbar" style="padding: 6px 7px 6px;">

                            <div class="col-xs-12 col-sm-6">
                                <div class="dt_action">
                                    <a class="btn btn-primary dt-add-btn" rel="tooltip"
                                       data-placement="bottom" data-original-title="添加菜单">
                                        <i class="fa fa-plus"></i> Add</a>
                                    <span class="margin-left-5"></span>
                                    <a class="btn btn-success dt-expand-btn" rel="tooltip"
                                       data-placement="bottom" data-original-title="展开所有">
                                        <i class="fa fa-hand-o-down"></i> Expand</a>
                                    <span class="margin-left-5"></span>
                                    <a class="btn btn-success dt-collapse-btn" rel="tooltip"
                                       data-placement="bottom" data-original-title="收起所有">
                                        <i class="fa fa-hand-o-up"></i> Collapse</a>
                                </div>
                            </div>
                            <div class="col-sm-6 col-xs-6 hidden-xs">
                                <div class="dt_refresh">
                                    <a class="btn btn-info dt-save-btn" rel="tooltip"
                                       data-placement="bottom" data-original-title="保存排序">
                                        <i class="fa fa-floppy-o"></i> Save</a>
                                    <a class="btn btn-link dt-refresh-btn" rel="tooltip"
                                       data-placement="bottom" data-original-title="刷新"><i
                                            class="fa fa-refresh"></i></a>
                                </div>
                            </div>
                        </div>
                        <!-- end menu table toolbar -->
                        <div id="menuTable" class="treetablepadding"></div>
                    </div>

                </div>
            </div>

        </article>
        <!-- WIDGET END -->
    </div>
    <!-- end row -->
</section>
<!-- end widget grid -->

<div id="menu-tree-dialog"></div>
<div id="menu-icon-dialog"></div>

<!-- menu form content -->
<div class="well dialog-well" id="menu-dialog" style="display: none;">

    <div class="widget-body no-padding">

        <form id="menu-form" action="${ctx}/sys/menu/save" method="post" class="smart-form">

            <fieldset>
                <div class="hide">
                    <input type="hidden" name="id"> 　
                </div>
                <section>
                    <label class="label">上级菜单</label>
                    <div id="parent-menu"></div>
                </section>
                <div class="row">
                    <section class="col col-6">
                        <label class="label">名称</label>
                        <label class="input">
                            <i class="icon-append fa fa-key"></i>
                            <input type="text" name="name" placeholder="菜单名称">
                            <b class="tooltip tooltip-bottom-right">菜单的显示名,必须设置</b>
                        </label>
                    </section>
                    <section class="col col-6">
                        <label class="label">类型</label>
                        <label class="select" rel="tooltip" data-placement="bottom"
                               data-original-title="通过设置菜单类型,可以把菜单归类">
                            <select name="target">
                                <!--:
                                    for(type in typeList!){
                                -->
                                <option value="${type.value!''}">${type.label!''}</option>
                                <!--:
                                    }
                                -->
                            </select><i></i>
                        </label>
                    </section>
                </div>
                <section>
                    <label class="label">页面链接</label>
                    <label class="input">
                        <i class="icon-append fa fa-link"></i>
                        <input type="text" name="href" placeholder="/sys/menu/list">
                        <b class="tooltip tooltip-bottom-right">点击菜单跳转的页面</b>
                    </label>
                </section>

                <section>
                    <label class="label">图标</label>
                    <div id="icon-menu" style="height:32px;" class="bordered"></div>
                </section>

                <div class="row">
                    <section class="col col-6">
                        <label class="label">排序</label>
                        <label class="input">
                            <i class="icon-append fa fa-sort-amount-asc"></i>
                            <input type="text" name="sort" placeholder="">
                            <b class="tooltip tooltip-bottom-right">排列顺序，升序</b>
                        </label>
                    </section>

                    <section class="col col-6">
                        <label class="label">是否可见</label>
                        <label class="select" rel="tooltip" data-placement="bottom"
                               data-original-title="该菜单或操作是否显示到系统菜单中">
                            <select name="isShow">
                                <!--:
                                    for(able in ableList!){
                                -->
                                <option value="${able.value!''}">${able.label!''}</option>
                                <!--:
                                    }
                                -->
                            </select> <i></i> </label>
                    </section>
                </div>

                <section>
                    <label class="label">权限标识</label>
                    <label class="input">
                        <i class="icon-append fa fa-recycle"></i>
                        <input type="text" name="permission" placeholder="sys:menu:edit">
                        <b class="tooltip tooltip-bottom-right">控制器中定义的权限标识，如：@RequiresPermissions("权限标识")</b>
                    </label>
                </section>

                <section>
                    <label class="label">备注信息</label>
                    <label class="textarea">
                        <i class="icon-append fa fa-comment"></i>
                        <textarea rows="4" name="remarks"></textarea>
                    </label>
                </section>

            </fieldset>

        </form>

    </div>
</div>
<!-- end menu form content -->

<script type="text/javascript">

    /* DO NOT REMOVE : GLOBAL FUNCTIONS!
     *
     * pageSetUp(); WILL CALL THE FOLLOWING FUNCTIONS
     *
     * // activate tooltips
     * $("[rel=tooltip]").tooltip();
     *
     * // activate popovers
     * $("[rel=popover]").popover();
     *
     * // activate popovers with hover states
     * $("[rel=popover-hover]").popover({ trigger: "hover" });
     *
     * // activate inline charts
     * runAllCharts();
     *
     * // setup widgets
     * setup_widgets_desktop();
     *
     * // run form elements
     * runAllForms();
     *
     ********************************
     *
     * pageSetUp() is needed whenever you load a page.
     * It initializes and checks for all basic elements of the page
     * and makes rendering easier.
     *
     */
    pageSetUp();

    /*
     * ALL PAGE RELATED SCRIPTS CAN GO BELOW HERE
     */
    // PAGE RELATED SCRIPTS
    // pagefunction
    var pagefunction = function () {

        var $menuForm = $('#menu-form');
        $menuForm.validate({
            // Rules for form validation
            rules: {
                // 为了不污染html代码,验证统一在js中
                'parent.name': {
                    required: true
                },
                name: {
                    required: true,
                    maxlength: 50
                },
                href: {
                    maxlength: 2000
                },
                sort: {
                    required: true,
                    digits: true,
                    maxlength: 10
                },
                permission: {
                    maxlength: 50
                },
                remarks: {
                    maxlength: 250
                }
            },

            // Messages for form validation,use default
            messages: {
                // 不覆盖使用默认js多语言文件
            },
            submitHandler: function (form) {
                // 遮罩
                var loadIndex = parent.layer.load(0, {shade: 0.4});

                $(form).ajaxSubmit({
                    dataType: "json",
                    success: function (data) {
                        parent.layer.close(loadIndex);

                        if (data && data.status == 'success') {
                            // 刷新表格
                            treetable.refresh();
                            parent.messageBox(data.message, "success");
                        } else {
                            parent.messageBox(data.message, "error");
                        }
                        // 显示
                        parent.layer.closeAll('page');
                    },
                    error: function () {
                        parent.layer.close(loadIndex);
                        parent.messageBox("修改菜单错误!", "error");
                    }
                });
                // always return false to prevent standard browser submit and page navigation
                return false;
            },
            // Do not change code below
            errorPlacement: function (error, element) {
                error.insertAfter(element.parent());
            }
        });

        /**
         * 根据类型获取类型label
         * @param value 类型value
         * @param type 1:type 2:able
         */
        function getLabel(value, type) {
            var dicts = [];
            if (type == 1) {
                dicts = eval('${typeJson!""}');
            } else {
                dicts = eval('${ableJson!""}');
            }
            // 设置默认显示type
            var label = value;
            if (dicts) {
                $.each(dicts, function (i, dict) {
                    if (dict['value'] == value) {
                        label = dict['label'];
                        return false;
                    }
                });
            }
            return label;
        }

        // 树表
        var treetable = new TreeTableData({
            databind: $('#menuTable').get(0),
            remote: true,
            dataurl: '${ctx}/sys/menu/list',
            parser: function (datas) {
                // 转换数据格式
                // old      {"id":"8","isNewRecord":false,"createDate":"2016-05-27 08:00:00",'icon':'fa fa-user',
                //          "updateDate":"2016-05-27 08:00:00","parentIds":"0,1,2,3,7,","name":"查看",
                //          "sort":10,"isShow":"0","permission":"sys:role:view","useable":"1","parentId":"7"}
                // new      parentId-->pid; icon:add new; leaf:false
                if (datas && !$.isEmptyObject(datas)) {
                    $.each(datas, function (name, value) {
                        value['pid'] = value['parentId'];
                        value['leaf'] = false;
                        if (value['icon'] == null) {
                            value['icon'] = 'fa fa-list-alt';
                        }
                    });
                }
                return datas;
            },
            columns: [
                {
                    data: 'name', width: "300px", title: '菜单名称',
                    render: function (value, row) {
                        return '<a href="javascript:" onclick="modifyMenu(' + "'" + row['id'] + "'"
                                + ')">' + value + '</a>';
                    }
                },
                {data: 'href', width: "150px", title: '链接'},
                {
                    data: 'sort', class: 'menu-sort', width: "60px", title: '排序', editable: true,
                    convert: function (tr) {
                        return $(tr).find('.menu-sort a').text();
                    },
                    render: function (value) {
                        return '<a href="#" data-type="text" data-placement="right" ' +
                                'data-title="输入菜单排序">' + value + '</a>';
                    }
                },
                {
                    data: 'isShow', width: "80px", title: '可见性',
                    // 可见性（0：隐藏；1: 显示；）
                    render: function (value) {
                        return '<div class="text-center"><span class="label label-default">' + getLabel(value, 2) + '</span></div>';
                    }
                },
                {data: 'permission', width: "150px", title: '权限标示'},
                {
                    data: 'id', width: "120px", title: '操作',
                    render: function (value) {
                        var actions = [];
                        actions.push({
                            'icon': 'fa fa-edit',
                            'title': '修改',
                            'onclick': "modifyMenu('" + value + "');"
                        });
                        actions.push({
                            'icon': 'fa fa-trash-o',
                            'title': '删除',
                            'onclick': "removeMenu('" + value + "');"
                        });
                        actions.push({'divider': true});
                        actions.push({
                            'icon': 'fa fa-plus',
                            'title': '添加下级菜单',
                            'onclick': "addNextMenu('" + value + "');"
                        });
                        return buildTableCellAction(actions);
                    }
                }
            ],
            onInitialized: function () {
                $("#menuTable").find(".btn-group").parent().css('padding', '2px 10px');
                // treetable.getTreeTable().treetable("expandAll");
                //make username editable
                $('.menu-sort a').editable({
                    validate: function (value) {
                        if ($.trim(value) == '')
                            return '不能为空,必须输入';
                        if (!/^\d+$/.test(value)) {
                            return '只能输入数字';
                        }
                    }
                });
            }
        });

        /**
         * 修改菜单
         */
        function modifyMenu(id) {
            var menu = null;
            var datas = treetable.getTableData();
            $.each(datas, function (index, value) {
                if (value != null && value['id'] == id) {
                    menu = value;
                    return true;
                }
            });
            if (menu != null) {
                menu['parent.id'] = menu['parentId'];
                if (menu['parentName'] == null) {
                    menu['parent.name'] = "功能菜单"
                } else {
                    menu['parent.name'] = menu['parentName'];
                }
            }
            form(menu);
        }

        /**
         * 删除菜单
         */
        function removeMenu(id) {
            layer.confirm('您真的要删除选择的数据及其子数据？', {
                        icon: 3,
                        title: '删除菜单',
                        btn: ['确定', '取消'], //按钮
                        shade: 0.4 //不显示遮罩
                    }, function (index) {
                        // send
                        ajaxCoomand({
                            url: '${ctx}/sys/menu/delete',
                            data: {id: id},
                            callback: function () {
                                treetable.refresh();
                            }
                        });

                        layer.close(index);
                    }
            );
        }

        /**
         * 添加下一级机构
         */
        function addNextMenu(id) {
            var data = null;
            var datas = treetable.getTableData();
            $.each(datas, function (index, value) {
                if (value != null && value['id'] == id) {
                    data = value;
                    return true;
                }
            });
            var menu = {};
            if (data != null) {
                // 当前节点作为父节点
                menu['parent.id'] = data['id'];
                menu['parent.name'] = data['name'];
            }
            form(menu);
        }

        /**
         * 初始化一个tree selecter, 之后通过refresh设置值
         */
        var menuTreeSelect = new TreeSelecter({
            databind: $('#parent-menu').get(0),
            // 对话框弹出对话框需要外部定义一个div
            databind_dialog: $('#menu-tree-dialog').get(0),
            title: '区域',
            name: 'parent.id',
            // 隐藏域值
            value: '0',
            // 输入框名称
            labelName: 'parent.name',
            // 输入框值
            labelValue: '',
            // 数据请求url地址,树结构数据地址
            dataurl: '${ctx}/sys/menu/treeData',
            // 根据当前用户是否是admin角色决定
            allowClear: "${isAdmin!false}"
        });

        // 如果是弹出框上的再次弹出,不能渲染到弹出框里面,只能新bind一个
        var menuIconSelect = new IconSelecter({
            databind: $('#icon-menu').get(0),
            // 对话框弹出对话框需要外部定义一个div
            databind_dialog: $('#menu-icon-dialog').get(0),
            title: '选择图标',
            name: 'icon',
            // 隐藏域值
            value: '',
            // 输入框值
            labelValue: ''
        });

        /**
         * 打开编辑框
         */
        function form(menu) {
            var opr = '添加';
            if (menu != null && !$.isEmptyObject(menu) && menu['id'] != null) {
                opr = "修改";
            }
            // 对话框
            layer.open({
                type: 1,
                title: opr + '菜单',
                shadeClose: false,
                shade: 0.4,
                area: ['735px', '600px'],   // 因为项目很多,无法自动适应,加入高度
                maxmin: true,
                content: $('#menu-dialog'),
                btn: ['确定', '取消'],
                success: function () {
                    // 当你需要在层创建完毕时即执行一些语句，可以通过该回调。success会携带两个参数，分别是当前层DOM当前层索引
                    // 这里可以通过发送ajax获取,也可通过表格选择时获取的行的值设置
                    var value = '1';
                    var labelValue = '功能菜单';
                    var params = {};
                    var icon = '';
                    debugger;
                    if (menu != null && !$.isEmptyObject(menu)) {
                        if (menu['id'] != null) {
                            $menuForm.find('input[name=id]').val(menu['id']);
                            params = {'extId': menu['id']};
                        }
                        $menuForm.find('input[name="parent.id"]').val(menu['parent.id']);
                        $menuForm.find('input[name=name]').val(menu['name']);
                        $menuForm.find('input[name=href]').val(menu['href']);
                        $menuForm.find('select[name=target]').val(menu['target']);
                        $menuForm.find('input[name=icon]').val(menu['icon']);
                        $menuForm.find('input[name=sort]').val(menu['sort']);
                        $menuForm.find('select[name=isShow]').val(menu['isShow']);
                        $menuForm.find('input[name=permission]').val(menu['permission']);
                        $menuForm.find('textarea[name=remarks]').val(menu['remarks']);

                        value = menu['parent.id'];
                        labelValue = menu['parent.name'];
                        icon = menu['icon'];
                    }
                    // 需要根据选择设置树
                    menuTreeSelect.refresh({
                        value: value,
                        labelValue: labelValue,
                        params: params
                    });
                    menuIconSelect.refresh({
                        value: icon,
                        labelValue: transIcon(icon)
                    });
                },
                end: function () {
                    // 无论是确认还是取消，只要层被销毁了，end都会执行，不携带任何参数
                    $menuForm.find('input[name=id]').val('');
                    $menuForm.find('input[name="parent.id"]').val('0');
                    $menuForm.find('input[name=name]').val('');
                    $menuForm.find('input[name=href]').val('');
                    $menuForm.find('select[name=target]').get(0).selectedIndex = 0;
                    $menuForm.find('input[name=icon]').val('');
                    $menuForm.find('input[name=sort]').val('');
                    $menuForm.find('select[name=isShow]').get(0).selectedIndex = 0;
                    $menuForm.find('input[name=permission]').val('');
                    $menuForm.find('textarea[name=remarks]').val('');
                },
                yes: function () { //或者使用btn1
                    // 按钮【确定】的回调
                    $menuForm.submit();
                },
                cancel: function (index) { //或者使用btn2
                    // 按钮【取消】的回调
                    layer.close(index);
                }
            });
        }

        function transIcon(icon) {
            if (icon != null && icon != '') {
                return icon.substring(6);
            }
            return "无";
        }

        // 注册
        window.modifyMenu = modifyMenu;
        window.removeMenu = removeMenu;
        window.addNextMenu = addNextMenu;

        var $menuList = $('#menu-list');
        // 添加
        $menuList.find('.dt-toolbar .dt-add-btn').on('click', function () {
            // 添加
            form();
        });

        // 展开
        $menuList.find('.dt-toolbar .dt-expand-btn').on('click', function () {
            //展开所有
            treetable.getTreeTable().treetable("expandAll");
        });
        // 收起
        $menuList.find('.dt-toolbar .dt-collapse-btn').on('click', function () {
            //收缩所有
            treetable.getTreeTable().treetable("collapseAll");
        });
        // 更新排序
        $menuList.find('.dt-toolbar .dt-save-btn').on('click', function () {
            // 更新节点排序
            var as = $('#menuTable').find('.menu-sort a');
            var datas = treetable.getTableData();
            if (datas != null && $.isArray(datas) && datas.length > 0 && as != null) {
                var ids = [];
                var sorts = [];
                $.each(as, function (index, value) {
                    ids.push(datas[index]['id']);
                    sorts.push(value.text);
                });
                // send
                ajaxCoomand({
                    url: '${ctx}/sys/menu/updateSort',
                    data: {ids: ids, sorts: sorts},
                    callback: function () {
                        treetable.refresh();
                    }
                });
            }
        });
        // 刷新
        $menuList.find('.dt-toolbar .dt-refresh-btn').on('click', function () {
            //刷新节点
            treetable.refresh();
        });

    };

    // destroy generated instances
    // pagedestroy is called automatically before loading a new page
    // only usable in AJAX version!
    var pagedestroy = function () {
        // 移除注册方法
        window.modifyMenu = undefined;
        window.removeMenu = undefined;
        window.addNextMenu = undefined;
        $('.menu-sort a').editable("destroy");
    };
    // end destroy

    // load related plugins
    loadScript("/static/js/plugin/jquery-tree/jquery.ztree.all-3.5.js", function () {
        loadScript("/static/js/plugin/jquery-tree/jquery.ztree.exhide-3.5.js", function () {
            loadScript("/static/js/extend/TreeSelecter.js", function () {
                loadScript("/static/js/extend/IconSelecter.js", function () {
                    loadScript("/static/js/plugin/treetable/jquery.treetable.js", function () {
                        loadScript("/static/js/plugin/x-editable/x-editable.js", function () {
                            loadScript("/static/js/plugin/jquery-form/jquery.form.js");
                            loadScript("/static/js/extend/TreeTableData.js", pagefunction);
                        })
                    })
                })
            })
        })
    });

</script>